package com.ruoyi.project.beautyflower;

import ai.advance.cmp.api.client.CMPAsyncClient;
import ai.advance.cmp.api.client.CMPSyncClient;
import ai.advance.cmp.api.client.bean.ResponseBean;
import ai.advance.cmp.api.client.bean.dto.*;
import ai.advance.cmp.api.client.bean.dto.query.*;
import ai.advance.cmp.api.client.enums.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.app.util.CalculationUtil;
import com.ruoyi.project.app.util.GenerateNum;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.*;

public class FaceScoreUtil {
    private static final Logger log = LoggerFactory.getLogger(FaceScoreUtil.class);


//    private static CMPSyncClient apiSyncClient = new CMPSyncClient("https://staging-api-cmp.advai.cn", "JUMEI", "8oQXDH4P3no4oviK");
//    private static CMPAsyncClient apiAsyncClient = CMPAsyncClient.getInstance("https://staging-api-cmp.advai.cn", "JUMEI", "8oQXDH4P3no4oviK");

    /**
     * 正式环境
     */
    private static CMPSyncClient apiSyncClient = new CMPSyncClient("https://production-api-cmp.ndmicro.com", "JUMEI", "REiw46hHyPr7hAR5rshYvHAY9OUyZx89");
    private static CMPAsyncClient apiAsyncClient = CMPAsyncClient.getInstance("https://production-api-cmp.ndmicro.com", "JUMEI", "REiw46hHyPr7hAR5rshYvHAY9OUyZx89");
    private static String TRAFFIC = "JUMEI";
    private static String PRODUCT = "JUMEI_CASHLOAN";




    public FaceScoreUtil() {
    }

    /**
     * 根据电话号码判断用户是否为聚美用户
     * @param mobileNumber
     * @return
     */
    public static ResponseBean queryUserInJuMeiByMobile(String mobileNumber) {
        TrafficUserByMobileQueryDTO queryDTO =new  TrafficUserByMobileQueryDTO();
        queryDTO.setTrafficIdentifier(TRAFFIC);
        queryDTO.setMobileNumber(mobileNumber);
        return apiSyncClient.queryUserInJuMeiByMobile(queryDTO);
    }

    /**
     * 颜值贷用户查询订单
     * @param userId
     * @return
     */
    public static ResponseBean queryOrderByUserId(String userId) {
        BaseDTO queryDTO=new BaseDTO();
        queryDTO.setTrafficIdentifier(TRAFFIC);
        queryDTO.setProductIdentifier(PRODUCT);
        queryDTO.setUserId(userId);
        return apiSyncClient.queryOrderByUserId(queryDTO);
    }
    /**
     * 颜值贷查询订单还款记录
     * @param userId
     * @return
     */
    public static ResponseBean queryRepaymentRecord(String userId) {
        BaseDTO queryDTO=new BaseDTO();
        queryDTO.setTrafficIdentifier(TRAFFIC);
        queryDTO.setProductIdentifier(PRODUCT);
        queryDTO.setUserId(userId);
        return apiSyncClient.queryRepaymentRecord(queryDTO);
    }

    /**
     * 根据订单号查询订单信息
     * @param orderQueryDTO
     * @return
     */
    public static ResponseBean queryOrderResult(OrderQueryDTO orderQueryDTO) {
        orderQueryDTO.setTrafficIdentifier(TRAFFIC);
        orderQueryDTO.setProductIdentifier(PRODUCT);
        return apiSyncClient.queryOrderResult(orderQueryDTO);
    }

    /**
     * 根据订单号查询还款计划
     * @param repaymentScheduleQueryDTO
     * @return
     */
    public static ResponseBean queryRepaymentScheduleResult(RepaymentScheduleQueryDTO repaymentScheduleQueryDTO) {
        repaymentScheduleQueryDTO.setTrafficIdentifier(TRAFFIC);
        repaymentScheduleQueryDTO.setProductIdentifier(PRODUCT);
        return apiSyncClient.queryRepaymentScheduleResult(repaymentScheduleQueryDTO);
    }

    /**
     * 颜值贷用户查询还款计划
     * @param userId
     * @return
     */
    public static ResponseBean queryNoRepaymentRecord(String userId) {
        BaseDTO queryDTO =new BaseDTO();
        queryDTO.setTrafficIdentifier(TRAFFIC);
        queryDTO.setProductIdentifier(PRODUCT);
        queryDTO.setUserId(userId);
        return apiSyncClient.queryNoRepaymentRecord(queryDTO);
    }

    /**
     * 通知还款
     * @param map
     * @return
     */
    public static ResponseBean createNotifyRepayment(Map<String,Object> map) {
        NotifyRepaymentCreateDTO createDTO = new NotifyRepaymentCreateDTO();
        createDTO.setTrafficIdentifier(TRAFFIC);
        createDTO.setProductIdentifier(PRODUCT);
        createDTO.setUserId(map.get("userId")+"");//用户id
        createDTO.setRepaymentActionId(map.get("actionId")+"");//还款流水号
        createDTO.setRepaymentDate(DateFormatUtils.format(new Date(), "yyyyMMdd"));//还款时间
        createDTO.setInstallments(Integer.parseInt(map.get("installments")+""));//还款总期数
        createDTO.setDefaultFine(BigDecimal.valueOf(0L));//还款违约金
        createDTO.setBankAccountName(map.get("bankAccountName")+"");//银行账户名
        createDTO.setBankCardNumber(map.get("bankCardNumber")+"");//银行卡号
        createDTO.setBankName(map.get("bankName")+"");//银行名称
        createDTO.setBankMobileNumber(map.get("bankMobileNumber")+"");//银行卡绑定的手机号
        BigDecimal repaymentAmount =new BigDecimal(map.get("repaymentAmount")+"");//还款金额
//                BigDecimal.valueOf(Double.valueOf(map.get("repaymentAmount")+""));
        JSONArray jsonArray = JSON.parseArray(map.get("details")+"");
        List<NotifyRepaymentDetailDTO> notifyRepaymentDetailDTOList = new ArrayList();//提前还款详细
        // 计算还款金额
        String money = repaymentAmount+"";
        int count = 0;
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONArray jsonArray1=jsonArray.getJSONArray(i);
            for (int i1 = 0; i1 < jsonArray1.size(); i1++) {
                JSONObject jsonObject = (JSONObject) jsonArray1.get(i1);
                //当该计划没有逾期是count进行+1
                if(StringUtils.isBlank(jsonObject.getString("defaultedInterestAmount")+"")){
                    count++;
                }
                NotifyRepaymentDetailDTO notifyRepaymentDetailDTO = new NotifyRepaymentDetailDTO();
                notifyRepaymentDetailDTO.setOrderId(jsonObject.getString("orderId")+"");//订单id
                notifyRepaymentDetailDTO.setInstallmentNo(Integer.parseInt(jsonObject.getString("installmentNo")+""));//还款分期号
                notifyRepaymentDetailDTO.setDuePrincipalAmount(jsonObject.getBigDecimal("duePrincipalAmount"));//应还款本金
                notifyRepaymentDetailDTO.setDueInterestAmount(jsonObject.getBigDecimal("repaymentInterestAmount"));//应还款利息
                notifyRepaymentDetailDTO.setRepaymentPrincipalAmount(jsonObject.getBigDecimal("duePrincipalAmount"));//实际还款本金
                BigDecimal repaymentInterestAmount = jsonObject.getBigDecimal("repaymentInterestAmount");//实际还款利息
                String remark = null;
                if(count>3){
                    if(StringUtils.isBlank(jsonObject.getString("defaultedInterestAmount")+"")){
                        notifyRepaymentDetailDTO.setRepaymentInterestAmount(BigDecimal.valueOf(0D));//实际还款利息
                        money = CalculationUtil.handleSubStr(money,repaymentInterestAmount+"", 2);//总金额减去当期还款计划的利息
                        remark = "提前还款减息";
                    }else{
                        notifyRepaymentDetailDTO.setRepaymentInterestAmount(repaymentInterestAmount);//实际还款利息
                    }
                }else{
                    notifyRepaymentDetailDTO.setRepaymentInterestAmount(repaymentInterestAmount);//实际还款利息
                }
                //逾期费用不为空时计算还款总金额及增加罚息
                if(StringUtils.isNotBlank(jsonObject.getString("defaultedInterestAmount")+"")){
                    money = CalculationUtil.handleAddStr(money,jsonObject.getBigDecimal("defaultedInterestAmount")+"", 2);//总金额加上逾期的利息
                    notifyRepaymentDetailDTO.setDefaultedInterestAmount(jsonObject.getBigDecimal("defaultedInterestAmount"));//应还罚息
                    notifyRepaymentDetailDTO.setRepaymentDefaultedInterestAmount(jsonObject.getBigDecimal("defaultedInterestAmount"));//实际还款罚息
                }else{
                    notifyRepaymentDetailDTO.setDefaultedInterestAmount(BigDecimal.valueOf(0L));//应还罚息
                    notifyRepaymentDetailDTO.setRepaymentDefaultedInterestAmount(BigDecimal.valueOf(0L));//实际还款罚息

                }
                notifyRepaymentDetailDTO.setRemark(remark);//备注，如利息减免等有用的信息

                notifyRepaymentDetailDTOList.add(notifyRepaymentDetailDTO);
            }
        }
        if (createDTO.getDefaultFine() == null) {
            createDTO.setDefaultFine(BigDecimal.valueOf(0L));
        }
        repaymentAmount=new BigDecimal(money);
        createDTO.setRepaymentAmount(repaymentAmount.add(createDTO.getDefaultFine()));//还款金额
        createDTO.setDetails(notifyRepaymentDetailDTOList);
        return apiSyncClient.createNotifyRepayment(createDTO);
    }


    public static void main(String[] args) {
//        ResponseBean responseBean= FaceScoreUtil.queryNoRepaymentRecord("369042387");
////        Map<String,Object> map=(Map<String,Object>)responseBean.getData();
//        List<Object> list=(List<Object>)responseBean.getData();
//        System.out.println(responseBean.getData());

        System.out.println( CalculationUtil.handleSubStr("95.5","1.5", 2));
    }


}
